import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Search from '../announcement/components/search';
import Table from '../announcement/components/fileList';
import { getData, getQueryVariable } from "../common/js/fetch";
import 'antd/dist/antd.css';
import 'lancoo-web-ui/dist/style.css'
import moment from 'moment';
import { DatePicker, Space, Spin, message, ConfigProvider, Drawer } from 'antd';
import {LgPaginationA} from "lancoo-web-ui";
import ReactJsonView from "react-json-view";
import zh_CN from 'antd/lib/locale-provider/zh_CN';
import "./index.scss";

const { RangePicker } = DatePicker;

const noticeNatureInfo = {
    "1": "校级",
    "3": "班级"
}

const tableHeader = [
    {
        name: '',
        width: "4%",
        textColor: "#999",
        key: 'index',
    },
    {
        name: '标题',
        width: "16%",
        textAlign: "left",
        padding: "0 10px",
        key: 'title',
    },
    {
        name: '发布者',
        width: "12%",
        textColor: "#999",
        textAlign: "left",
        padding: "0 10px",
        key: 'userText'
    },
    {
        name: '发布时间',
        width: "12%",
        textColor: "#999",
        key: 'releaseTime'
    },
    {
        name: '通知类型',
        width: "8%",
        key: 'noticeNatureText'
    },
    {
        name: '消息推送',
        width: "8%",
        key: 'messageResult'
    },
    {
        name: '楼牌推送',
        width: "8%",
        key: 'buildResult'
    },
    {
        name: '班牌推送',
        width: "8%",
        key: 'classResult'
    },
    {
        name: '广播终端推送',
        width: "8%",
        key: 'boardResult'
    },
    {
        name: '学校官网推送',
        width: "8%",
        key: 'schoolResult'
    },
    {
        name: '用户选择',
        width: "8%",
        key: 'userResult'
    },
]

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loadVisible: true,
            userInfo: {},
            sysInfo: {},
            token: "",
            total: 0,
            logList: [],
            pageSize: 10,
            pageSizeList: [
                {text:"每页10条",info: 10},
                {text:"每页20条",info: 20},
                {text:"每页30条",info: 30},
            ],
            pageNum: 1,
            keyword: "",
            startDate: "",
            endDate: "",
            detailInfo: {},
            detailVisible: false,
            noticeInfo: {},
            noticeVisible: false
        };
    }

    componentDidMount() {
        let token = getQueryVariable("lg_tk") || sessionStorage.getItem("token") || localStorage.getItem("token");
        if(token){
            getData('api/commons/school/system/info', {
                token
                }).then(data => {
                return data.json()
                }).then(json => {
                if (json.code === "200" && json.data) {
                    let sysInfo = json.data;
                    // window.location.href = data.baseUrl + `${data.iscVersion>=4? "login.html":"/UserMgr/Login/Login.aspx"}?lg_sysid=220&lg_preurl=` + url;
                    //获取用户信息
                    getData('api/commons/school/user/self', {
                        token,
                        identityCode: getQueryVariable("lg_ic")
                    }).then(data => {
                        return data.json()
                    }).then(json => {
                        if (json.code === "200" && json.data) {
                            let { data } = json;
                            this.setState({
                                token,
                                sysInfo,
                                userInfo: data
                            }, ()=>{
                                this.getLogList();
                            })
                        }
                    });
                }
            });
        }
    }

    getLogList = () => {
        let { token, pageSize, pageNum, sysInfo, keyword, startDate, endDate } = this.state;
        getData(`api/log/list/page/${pageNum}/${pageSize}`, {
            schoolId: sysInfo.schoolId,
            keyword,
            type: 1,
            beginTime: startDate? startDate + " 00:00:00": "",
            endTime: endDate? endDate + " 23:59:59": "",
        })
        .then(res=>res.json())
        .then(res=>{
            if(res.code === "200" && res.data){
                let { records, total } = res.data;
                this.setState({
                    total,
                    loadVisible: false,
                    logList: records
                })
            }
        });
    }

    searchList = (value) => {
        this.setState({
            keyword: value,
            pageNum: 1
        }, ()=>{
            this.getLogList();
        })
    }

    changeDate = (date, date2) => {
        this.setState({
            startDate: date2[0],
            endDate: date2[1],
            pageNum: 1
        }, ()=>{
            this.getLogList();
        })
    }

    changePageSize = (value) => {
        this.setState({
            pageSize: value.info,
            pageNum: 1
        },()=>{
            this.getLogList();
        })
    }

    getNoticeInfo = (value) => {
        let obj = {...value};
        delete obj.recordList;
        this.setState({
            noticeInfo: obj,
            noticeVisible: true
        })
    }

    getDetailInfo = (value) => {
        this.setState({
            detailInfo: value,
            detailVisible: true
        })
    }
    render() {
        let {
            logList,
            keyword,
            total,
            detailVisible,
            loadVisible,
            detailInfo,
            pageNum,
            pageSize,
            pageSizeList,
            noticeInfo,
            noticeVisible
        } = this.state;
        let updateList = logList.map((item, index)=>{
            let obj = {
                ...item,
                noticeNatureText: (
                    <span className='notice-info'>
                        {noticeNatureInfo[item.noticeNature]||"--"}
                        <span className='detaillogo' onClick={()=>this.getNoticeInfo(item)}></span>
                    </span>
                ),
                userText: `${item.userName}(${item.userId})`,
                messageResult: "无推送",
                buildResult: "无推送",
                boardResult: "无推送",
                classResult: "无推送",
                schoolResult: "无推送",
                userResult: "无推送",
            };
            obj.index = index+1;
            Array.isArray(obj.recordList) &&
            obj.recordList.forEach((child)=>{
                if(child.sysId === "210"){
                    obj.messageResult = (
                        <span className={`result-container ${child.result === "1"? "green": child.result === "2"? "red": ""}`}>
                            {child.result === "1"? "正常": child.result === "2"? "异常": "无推送"}
                            {
                                child.result === "1"? <span className='detaillogo' onClick={()=>this.getDetailInfo(child)}></span>: 
                                child.result === "2"? <span className='logo-container'><span className='errorlogo' title={child.reason}></span><span className='detaillogo' onClick={()=>this.getDetailInfo(child)}></span></span>:
                                ""
                            }
                        </span>
                    );
                }
                if(child.sysId === "E36"){
                    obj.classResult = (
                        <span className={`result-container ${child.result === "1"? "green": child.result === "2"? "red": ""}`}>
                            {child.result === "1"? "正常": child.result === "2"? "异常": "无推送"}
                            {
                                child.result === "1"? <span className='detaillogo' onClick={()=>this.getDetailInfo(child)}></span>: 
                                child.result === "2"? <span className='logo-container'><span className='errorlogo' title={child.reason}></span><span className='detaillogo' onClick={()=>this.getDetailInfo(child)}></span></span>:
                                ""
                            }
                        </span>
                    );
                }
                if(child.sysId === "E29"){
                    obj.buildResult = (
                        <span className={`result-container ${child.result === "1"? "green": child.result === "2"? "red": ""}`}>
                            {child.result === "1"? "正常": child.result === "2"? "异常": "无推送"}
                            {
                                child.result === "1"? <span className='detaillogo' onClick={()=>this.getDetailInfo(child)}></span>: 
                                child.result === "2"? <span className='logo-container'><span className='errorlogo' title={child.reason}></span><span className='detaillogo' onClick={()=>this.getDetailInfo(child)}></span></span>:
                                ""
                            }
                        </span>
                    );
                }
                if(child.sysId === "M20"){
                    obj.boardResult = (
                        <span className={`result-container ${child.result === "1"? "green": child.result === "2"? "red": ""}`}>
                            {child.result === "1"? "正常": child.result === "2"? "异常": "无推送"}
                            {
                                child.result === "1"? <span className='detaillogo' onClick={()=>this.getDetailInfo(child)}></span>: 
                                child.result === "2"? <span className='logo-container'><span className='errorlogo' title={child.reason}></span><span className='detaillogo' onClick={()=>this.getDetailInfo(child)}></span></span>:
                                ""
                            }
                        </span>
                    );
                }
                if(child.sysId === "E46"){
                    obj.schoolResult = (
                        <span className={`result-container ${child.result === "1"? "green": child.result === "2"? "red": ""}`}>
                            {child.result === "1"? "正常": child.result === "2"? "异常": "无推送"}
                        </span>
                    );
                }
                if(child.sysId === "000"){
                    obj.userResult = (
                        <span className={`result-container ${child.result === "1"? "green": child.result === "2"? "red": ""}`}>
                            {child.result === "1"? "正常": child.result === "2"? "异常": "无推送"}
                        </span>
                    );
                }
            })
            return obj;
        })
        return (
            <Spin spinning={loadVisible} tip='加载中...'>
            <div className="notice-log-page">
                <div className='notice-log-page-top'>
                    <div className='notice-log-page-top-left'>
                        <RangePicker className='log-date-select' onChange={this.changeDate} />
                        <span className='log-list-total'>共<span>{total}</span>条记录</span>
                    </div>
                    <Search searchMethod={this.searchList} placeholder="搜索标题/发布者姓名..." />
                </div>
                <Table
                tableHeader={tableHeader}
                pageSize={pageSize}
                scrollbar={false}
                emptyText={keyword? "搜素结果为空": "暂无内容~"}
                data={updateList}
                ></Table>

                {
                    total > pageSize?
                    <div className="menu_pagination">
                        <LgPaginationA
                        total={Math.ceil(total/pageSize)}
                        size="normal"
                        currentPage={pageNum}
                        onChangePage={(value)=>{
                            this.setState({
                                pageNum: value,
                            }, ()=>{
                                this.getLogList();
                            })
                        }}
                        errorPage={() => {
                            message.warn(`最多${Math.ceil(total / 10)}页`);
                        }}
                        pageSizeList = {pageSizeList}
                        pageSizeIndex = {0}
                        pageSizeSelect = {this.changePageSize}
                        ></LgPaginationA>
                    </div>:
                    ""
                }

                <Drawer 
                title="通知参数详情" 
                width={900}
                className='detail-drawer'
                onClose={()=>this.setState({noticeVisible: false})} 
                visible={noticeVisible}>
                    <div className="info-option" style={{marginTop: 12}}>
                        <span className='option-name' style={{marginTop: 10}}>参数:</span>
                        <ReactJsonView
                        name={false}
                        indentWidth={4}
                        iconStyle='triangle'
                        src={noticeInfo}
                        displayObjectSize={false}
                        displayDataTypes={false}
                        enableClipboard={false}
                        sortKeys
                        quotesOnKeys={true} />
                    </div>
                </Drawer>

                <Drawer 
                title="通知推送详情" 
                width={900}
                className='detail-drawer'
                onClose={()=>this.setState({detailVisible: false})} 
                visible={detailVisible}>
                    <div className="info-option">
                        <span className='option-name'>责任方:</span>
                        <span className='option-value'>{detailInfo.sysName}</span>
                    </div>
                    {
                        detailInfo.reason?
                        <div className="info-option">
                            <span className='option-name'>原因:</span>
                            <span className='option-value'>{detailInfo.reason}</span>
                        </div>:
                        ""
                    }
                    <div className="info-option">
                        <span className='option-name'>接口:</span>
                        <span className='option-value'>{detailInfo.requestUrl}</span>
                    </div>
                    <div className="info-option" style={{marginTop: 12}}>
                        <span className='option-name' style={{marginTop: 10}}>参数:</span>
                        <ReactJsonView
                        name={false}
                        indentWidth={4}
                        iconStyle='triangle'
                        src={detailInfo.requestParameters? JSON.parse(detailInfo.requestParameters): {}}
                        displayObjectSize={false}
                        displayDataTypes={false}
                        enableClipboard={false}
                        sortKeys
                        quotesOnKeys={true} />
                    </div>
                </Drawer>
            </div>
            </Spin>
        );
    }
}
ReactDOM.render( <ConfigProvider locale={zh_CN}><App /></ConfigProvider>, document.getElementById('root'));